#!/usr/bin/env python3
"""
中文字体安装和验证脚本

用于检查系统中文字体支持，并提供安装建议
"""

import os
import sys
import logging
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class ChineseFontManager:
    """中文字体管理器"""
    
    def __init__(self):
        self.chinese_font_paths = [
            # Ubuntu/Debian 中文字体
            "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
            "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", 
            "/usr/share/fonts/truetype/arphic/ukai.ttc",
            "/usr/share/fonts/truetype/arphic/uming.ttc",
            "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
            "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf",
            
            # CentOS/RHEL 中文字体
            "/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc",
            "/usr/share/fonts/wqy-microhei/wqy-microhei.ttc",
            
            # macOS 中文字体
            "/System/Library/Fonts/PingFang.ttc",
            "/System/Library/Fonts/STHeiti Light.ttc",
            "/System/Library/Fonts/Arial Unicode MS.ttf",
            "/Library/Fonts/Arial Unicode MS.ttf",
            
            # Windows 中文字体
            "C:/Windows/Fonts/simsun.ttc",
            "C:/Windows/Fonts/simhei.ttf", 
            "C:/Windows/Fonts/msyh.ttc",
            "C:/Windows/Fonts/arial.ttf"
        ]
        
        self.available_fonts = []
        self.best_font = None
        
    def scan_fonts(self):
        """扫描可用的中文字体"""
        logger.info("扫描系统中文字体...")
        
        for font_path in self.chinese_font_paths:
            if os.path.exists(font_path):
                try:
                    # 尝试加载字体
                    font = ImageFont.truetype(font_path, 16)
                    self.available_fonts.append({
                        'path': font_path,
                        'name': Path(font_path).name,
                        'font_obj': font
                    })
                    logger.info(f"✓ 找到字体: {font_path}")
                except Exception as e:
                    logger.debug(f"字体加载失败 {font_path}: {e}")
        
        if self.available_fonts:
            # 选择最佳字体（优先选择文泉驿或思源字体）
            for font_info in self.available_fonts:
                if any(name in font_info['name'].lower() for name in ['wqy', 'noto', 'source']):
                    self.best_font = font_info
                    break
            
            if not self.best_font:
                self.best_font = self.available_fonts[0]
                
            logger.info(f"✓ 选择字体: {self.best_font['name']}")
        else:
            logger.warning("⚠️ 未找到可用的中文字体")
            
        return len(self.available_fonts) > 0
    
    def test_chinese_rendering(self):
        """测试中文字符渲染"""
        if not self.best_font:
            logger.error("没有可用的中文字体进行测试")
            return False
            
        try:
            # 创建测试图像
            test_img = Image.new('RGB', (400, 200), 'white')
            draw = ImageDraw.Draw(test_img)
            
            test_text = "测试中文字体渲染效果"
            font = self.best_font['font_obj']
            
            # 绘制测试文本
            draw.text((50, 50), test_text, fill='black', font=font)
            
            # 保存测试图像
            test_output = "font_test.png"
            test_img.save(test_output)
            
            logger.info(f"✓ 中文渲染测试完成，结果保存到: {test_output}")
            return True
            
        except Exception as e:
            logger.error(f"中文渲染测试失败: {e}")
            return False
    
    def install_font_suggestions(self):
        """提供字体安装建议"""
        if self.available_fonts:
            return
            
        logger.info("\n🔧 中文字体安装建议:")
        
        # 检测操作系统
        import platform
        os_name = platform.system().lower()
        
        if os_name == 'linux':
            distro = self._detect_linux_distro()
            
            if 'ubuntu' in distro or 'debian' in distro:
                logger.info("Ubuntu/Debian 系统:")
                logger.info("  sudo apt-get update")
                logger.info("  sudo apt-get install fonts-wqy-zenhei fonts-wqy-microhei")
                logger.info("  sudo apt-get install fonts-noto-cjk fonts-noto-cjk-extra")
                
            elif 'centos' in distro or 'rhel' in distro or 'fedora' in distro:
                logger.info("CentOS/RHEL/Fedora 系统:")
                logger.info("  sudo yum install wqy-zenhei-fonts wqy-microhei-fonts")
                logger.info("  # 或者对于较新版本:")
                logger.info("  sudo dnf install google-noto-sans-cjk-fonts")
                
        elif os_name == 'darwin':  # macOS
            logger.info("macOS 系统:")
            logger.info("  系统应该自带中文字体，请检查系统字体册")
            logger.info("  或使用 Homebrew 安装: brew install font-source-han-sans")
            
        elif os_name == 'windows':
            logger.info("Windows 系统:")
            logger.info("  系统应该自带中文字体（如宋体、黑体）")
            logger.info("  请检查 C:/Windows/Fonts/ 目录")
        
        logger.info("\n📥 手动下载字体:")
        logger.info("  1. 文泉驿字体: http://wenq.org/")
        logger.info("  2. 思源字体: https://github.com/adobe-fonts/source-han-sans")
        logger.info("  3. Noto字体: https://www.google.com/get/noto/")
    
    def _detect_linux_distro(self):
        """检测Linux发行版"""
        try:
            with open('/etc/os-release', 'r') as f:
                content = f.read().lower()
                return content
        except:
            return ""
    
    def create_font_config(self):
        """创建字体配置文件"""
        if not self.best_font:
            return None
            
        font_config = {
            'font_path': self.best_font['path'],
            'font_name': self.best_font['name'],
            'title_size': 24,
            'content_size': 16,
            'support_chinese': True
        }
        
        config_file = "font_config.json"
        import json
        with open(config_file, 'w', encoding='utf-8') as f:
            json.dump(font_config, f, ensure_ascii=False, indent=2)
            
        logger.info(f"✓ 字体配置已保存: {config_file}")
        return font_config


def main():
    """主函数"""
    print("🔤 中文字体检查和配置工具")
    print("=" * 40)
    
    manager = ChineseFontManager()
    
    # 扫描字体
    has_fonts = manager.scan_fonts()
    
    if has_fonts:
        print(f"\n✅ 找到 {len(manager.available_fonts)} 个可用中文字体")
        
        # 显示可用字体列表
        print("\n📋 可用字体列表:")
        for i, font_info in enumerate(manager.available_fonts, 1):
            print(f"  {i}. {font_info['name']}")
            print(f"     路径: {font_info['path']}")
        
        # 测试渲染
        print(f"\n🧪 测试最佳字体: {manager.best_font['name']}")
        success = manager.test_chinese_rendering()
        
        if success:
            print("✅ 中文字体渲染正常")
            
            # 创建配置文件
            config = manager.create_font_config()
            print("✅ 字体配置文件创建成功")
            
        else:
            print("❌ 中文字体渲染异常")
    
    else:
        print("❌ 未找到可用的中文字体")
        manager.install_font_suggestions()
    
    print("\n" + "=" * 40)
    print("检查完成！")


if __name__ == "__main__":
    main()